<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title></title>
</head>

<body>
</body>
<script>
  var arr = [

    {
      id: 1,
      groupCode: '111',
      groupName: 'susu',
      name: 'test01'
    },
    {
      id: 2,
      groupCode: '111',
      groupName: 'susu',
      name: 'test02'
    },
    {
      id: 3,
      groupCode: '222',
      groupName: 'susu2',
      name: 'test03'
    },
    {
      id: 4,
      groupCode: '333',
      groupName: 'susu3',
      name: 'test04'
    },
    {
      id: 5,
      groupCode: '333',
      groupName: 'susu3',
      name: 'test05'
    },
    {
      id: 6,
      groupCode: '333',
      groupName: 'susu3',
      name: 'test06'
    },
  ];
  console.log(arr)
  // 普通对象处理
  function groupByKey(key, arr, key1) {
    let map = {},
      resData = [];
    arr.map(item => {
      if (!map[item[key]]) {
        map[item[key]] = [item]
      } else {
        map[item[key]].push(item)
      }
    })
    Object.keys(map).forEach(i => {
      console.log(map, i)
      resData.push({
        [key]: i,
        [key1]: map[i][0][key1],
        list: map[i]
      })
    })
    return resData;
  }
  console.log(groupByKey('groupCode', arr, 'groupName'))
  // map处理
  function groupByMap(arr, f, keyId, keyName) {
    let result = [];
    //初始化 Map, 用来存储键值对
    let map = new Map()
    arr.forEach(function(obj) {
      //根据传入的函数，对数组中的每一个对象产生一个 key值，并将key值相等的对象分为一组
      let key = f(obj)
      map.set(key, (map.get(key) || []))
      map.get(key).push(obj)
    });
    // console.log(map.entries())
    //map-转数组
    // 法一：
    let arr1 = Array.from(map);
    // 法2：
    // console.log([...map]);
    // // 法3：
    // let arr1 = [];
    // for (var key of map) {
    //   arr1.push(key);
    // }
    // console.log('arr1', arr1);
    arr1.forEach(item => {
      result.push({
        [keyId]: item[0],
        [keyName]: item[1][0][keyName],
        list: item[1]
      })
    })
    return result;
  }
  console.log(groupByMap(arr, item => item.groupCode, 'groupCode', 'groupName'))
</script>

</html>